package com.zx.zxblog.service.Impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zx.zxblog.entity.dto.LoginDTO;
import com.zx.zxblog.entity.pojo.User;
import com.zx.zxblog.mapper.UserMapper;
import com.zx.zxblog.service.UserService;
import com.zx.zxblog.util.R;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpSession;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {


    @Override
    public User checkUser(String username, String password) {
        //        MD5加密
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(password.getBytes());

        User user = getBaseMapper().selectOneByUsernameAndPassword(username, md5DigestAsHex);

        return user;
    }

    @Override
    public R login(LoginDTO loginDTO, HttpSession session) {
        User user = checkUser(loginDTO.getUsername(), loginDTO.getPassword());
        if (user == null) {
            return R.error("用户名或密码错误");
        }
        // 登录
        StpUtil.login(user.getId());
        //密码置空
        user.setPassword(null);
        // 保存用户
        session.setAttribute("user",user);
        // 第3步，返回token给前端
        return R.success();
    }
}
